package imageMarge

import (
	"changeme/imageMarge/entity"
	"fmt"
	"image"
	"image/draw"
	"image/png"
	"log"
	"math"
	"os"

	_ "golang.org/x/image/bmp"
)

func MargeResAny(files []string, p_out string) []entity.Plist {

	fs := make([]os.FileInfo, len(files))

	for k, v := range files {
		f, err := os.Stat(v)
		if err != nil {
			log.Println(err.Error())
			continue
		}
		fs[k] = f
	}

	mx, my := getMaxCountXY(len(fs))
	//图的集合
	img_array := make([]entity.ImgBean, 0)

	//填文件，计算目标图片位置

	for i, f := range fs {
		if f.IsDir() {
			continue
		}
		b := entity.ImgBean{}
		b.FileName = f.Name()
		b.Img = getImg(files[i])
		b.X = i % mx
		b.Y = i / mx
		img_array = append(img_array, b)
	}
	ps := make([]entity.Plist, len(img_array))

	line_max_height := 0
	max_x := 0

	newImg := image.NewNRGBA(image.Rect(0, 0, 10000, 10000)) //创建一个新RGBA图像
	for i := 0; i < my; i++ {

		temp_arr := make([]entity.ImgBean, mx)
		if i == my-1 { //最后一行
			temp_arr = img_array[0:]
		} else {
			temp_arr = img_array[0:mx] //每行的图片数量
			img_array = img_array[mx:]
		}
		temp_h := 0
		temp_w := 0
		for k, v := range temp_arr {
			v.X = temp_w * 1          //x便宜
			v.Y = line_max_height * 1 //y 偏移

			//拼图
			draw.Draw(newImg, newImg.Bounds(), v.Img, image.Pt(v.X*-1, v.Y*-1), draw.Over) //画上第一张缩放后的图片s
			p := entity.Plist{
				Name:   v.FileName,
				X:      v.X,
				Y:      v.Y,
				Width:  v.Img.Bounds().Max.X,
				Height: v.Img.Bounds().Max.Y,
				Ox:     0,
				Oy:     0,
			}
			ps[i*mx+k] = p

			//计算本行的最大高度
			if v.Img.Bounds().Max.Y > temp_h {
				temp_h = v.Img.Bounds().Max.Y
			}
			temp_w += v.Img.Bounds().Max.X //累计行宽
		}
		if temp_w > max_x { //计算最大宽度
			max_x = temp_w
		}
		line_max_height += temp_h
	}
	//fmt.Println(max_x,line_max_height)
	//判断输出文件是否存在

	if p_out != "" {
		outFile, _ := os.Create(p_out)
		defer outFile.Close()

		png.Encode(outFile, newImg.SubImage(image.Rect(0, 0, max_x, line_max_height)))

	}

	fmt.Println("OK", ps)
	return ps
}

func getMaxCountXY(sum int) (int, int) {
	f := float64(sum)
	ff := math.Sqrt(f)
	x := int(math.Round(ff))
	y := int(ff + 1)
	return x, y
}

func getImg(p string) image.Image {
	f, e := os.Open(p)
	if e != nil {
		fmt.Println(e)
		return nil
	}
	var (
		img1 image.Image
		err  error
		ss   string
	)
	if img1, ss, err = image.Decode(f); err != nil {
		fmt.Println(ss)
		fmt.Println(err)
		return nil
	}
	return img1

}
